﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SharpShare.Storage.FileSystem {
    internal class FileDataProvider : IStorageDataProvider {
        private object _synclock = new object();
        private FileStream _stream;

        public FileDataProvider(FileStorageItem item, StorageFileAccess accessMode, StorageFileAccess shareMode) {
            this.StorageItem = item;
            this.AccessMode = accessMode;
            this.ShareMode = shareMode;

            FileAccess fileAccess = accessMode.MapToFileAccess();
            FileShare fileShare = shareMode.MapToFileShare();
 
            _stream = new FileStream(item.Info.FullName, FileMode.Open, fileAccess, fileShare);
        }

        public StorageFileAccess AccessMode { get; private set; }
        public StorageFileAccess ShareMode { get; private set; }
        public FileStorageItem StorageItem { get; private set; }

        #region IStorageDataProvider Members

        long IStorageDataProvider.Length {
            get { return _stream.Length; }
        }

        StorageFileAccess IStorageDataProvider.AccessMode {
            get { return StorageFileAccess.ReadWrite; }
        }

        int IStorageDataProvider.Read(long position, byte[] buffer, int offset, int length) {
            lock (_synclock) {
                _stream.Position = position;
                return _stream.Read(buffer, offset, length);
            }
        }

        void IStorageDataProvider.Write(long position, byte[] buffer, int offset, int length) {
            lock (_synclock) {
                _stream.Position = position;
                _stream.Write(buffer, offset, length);
            }
        }

        void IStorageDataProvider.Flush(bool synchronize) {
            lock (_synclock) {
                _stream.Flush(synchronize);
            }
        }

        void IStorageDataProvider.Close() {
            _stream.Close();
        }

        void IStorageDataProvider.SetLength(long length) {
            lock (_synclock) {
                _stream.SetLength(length);
            }
        }

        #endregion
    }
}
